package com.fecean.aabbc.netty.server.prod7;

import com.fecean.aabbc.netty.dispatcher7.ChannelSender;
import com.fecean.aabbc.netty.message7.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

/**
 ** 客户端发送
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-03-12 16:44
 * @blame Team
 */
@Slf4j
@Component
public class NettyClientSender {

    /**
     ** 客户端连接池
     */
    @Resource
    NettyClientPool nettyClientPool;

    /**
     ** 通道发送对象
     */
    @Resource
    ChannelSender channelSender;

    /**
     ** 发送通知
     *
     * @param tenantId 租户ID
     * @param cinemaCode 影院编码
     * @param content 消息内容
     */
    public void sendNotice(String tenantId, String cinemaCode, String content){
        Optional<NettyClientWrapper> optionalChannel = nettyClientPool.getClient(tenantId, cinemaCode);
        optionalChannel.ifPresent(client ->
                channelSender.sendNotice(client.getChannel(), tenantId, cinemaCode, content));
    }

    /**
     ** 发送请求并接收响应结果
     *
     * @param tenantId 租户ID
     * @param cinemaCode 影院编码
     * @param content 消息内容
     * @return ResponseMessage响应结果
     */
    public ResponseMessage sendRequest(String tenantId, String cinemaCode, String content){
        Optional<NettyClientWrapper> optionalChannel = nettyClientPool.getClient(tenantId, cinemaCode);
        return optionalChannel.map(nettyClientWrapper -> channelSender.sendRequest(
                nettyClientWrapper.getChannel(), tenantId, cinemaCode, content)).orElse(null);
    }

}
